const api = require('@/static/js/api.js')
const utils = require('@/static/js/utils.js')
const Config = require('@/config.js')
const userModules = { //全局变量定义
	// namespaced: true,
	state: {
		hasLogin: false,
		isAuthPhone: false,
		isAuthUserInfo: false,
		isAuthLocation: false,
		isSeller: false, //===是否有店员端，查看权限
		isReferrer: false, //===是否未推荐人
		isChannel: false, //===是否为渠道
		openId: '',
		unionId: '',
		isExpires: false, //===APP使用到期
		points: 0, //===积分
		appAvatar:"",
		appNickName:"",
		authTiktokInfo: false,
		authTiktokAuthTime:null,
		authTiktokPermission: false,
		authTiktokPermissionValidStartTime:"",
		authTiktokPermissionValidEndTime:"",
		//=买家信息
		buyerObj: {
			id: '',
			uuid: '', //和置业顾问统一ID
			name: '',
			avatar: '/static/img/user_img_ntx.png',
			phone: '',
			salesmanId: '', // 通用ID,   IM聊天用---顾客ID,
			salesmanEmployId: '', //           IM聊天用---置业顾问ID
			salesmanName: '', // 客服名字
			officalAccountId: "", // 公众号ID
		},
		//==卖家信息
		sellerObj: {
			id: '', //卖家唯一的ID
			uuid: '', //和买家统一ID
			wechatCode: '',
			personSignature: '',
			name: '',
			nickname: '',
			avatar: '/static/img/user_img_ntx.png',
			phone: '',
			post: '', //职务名称
			qrcodeImage: '',
			wechatQrcode: '',
			cardShareTitle: '',
			cardShareImage: '',
			officalAccountId: '',
			roleName: '',
		},
		shopInfo: {
			allowEditUser: true,
			multiProject: false,
			tiktokAppId: "",	// appId   tt********
			wechatAppOriginId:"", //原始id gh_************
			panoramaUrl: 'https://talkyi.fzzkzh.com/wxinf/toindexv.do?pid=1000',
			address: "",
			location: {
				location: '',
				longitude: '',
			},
			name: '',
			indexModals: [{
				title: '项目热点',
				code: 'hotSpot'
			}, {
				title: '项目信息',
				code: 'projectInfo'
			}, {
				title: '楼盘动态',
				code: 'projectTrend'
			}],
			indexBigImage: '',
			entranceImagePath: '',
			trafficImagePath: '', //交通配套
			buildingImagePath: '', //楼盘信息
			contactImagePath: '', //联系我们
			unitTypeImagePath: '', //户型鉴赏
			news: '',
			newsImagePath: '',
			visitorNum: '...',
			layoutList: [],
			shareImage: '',
			sandBoxImage: '',
			shareInfo: '',
			privacyUrl: '',
			userAgreeUrl: '',
			logo: "",
			officalAccountUrl: '',
			authrizedOrder: ['phone', 'userInfo', 'location'],
			indexActivity: {},
			isEnInvite: false,
			tools: [],

			addCustomerManual: false,
			authInfo: [],

			audioType: 0,

			wxappIndexWholeConfig: {
				margin: 18,
				backgroundColor: '#ffffff',
				vrTop: '50%',
				pointerTop: '63%',
				vrUrl: 'https://etalk.obs.cn-south-1.myhuaweicloud.com/vrAm.gif',
				pointerUrl: '../../../static/image/icon_click.png',
				moveUrl: "../static/image/icon_move.png",
				disableSandbox: false,
			},
			pointsMallEnable: false, //积分商城是否开启

			hidePhone: false, //报备是否隐藏部分号码
			moreAuth: false, //是否连续授权
			disableSandbox: false, //项目禁用有沙盘
		},
	},
	// getters: {
	//     hasLogin: state => state.hasLogin,
	//     avatarUrl: state => state.avatarUrl,
	//     nickName: state => state.nickName,
	//     openId: state => state.openId,
	//     userId: state => state.userId,
	//     unionId: state => state.unionId,
	// },
	mutations: {	
		setProjectsInfo(state, flag) {
			if (flag) {
				state.shopInfo.multiProject = true;
			} else {
				state.shopInfo.multiProject = false;
			}
		},

		setShopInfo(state, info) {
			if (info.miniAppOriginId){
				state.shopInfo.wechatAppOriginId = info.miniAppOriginId
			}	
			if (info.ttAppid){
				state.shopInfo.tiktokAppId = info.ttAppid
			}
			if (info.showMall) {
				state.shopInfo.pointsMallEnable = true;
			}
			if (info.allowEditUser != null) {
				state.shopInfo.allowEditUser = info.allowEditUser
			}
			if (info.multiProject) {
				state.shopInfo.multiProject = true
			} else {
				state.shopInfo.multiProject = false
			}

			if (info.audioType == 1) {
				state.shopInfo.audioType = 1
			} else {
				state.shopInfo.audioType = 0
			}

			if (info.moreAuth) {
				state.shopInfo.moreAuth = true
			} else {
				state.shopInfo.moreAuth = false
			}

			if (info.disableSandbox) {
				state.shopInfo.disableSandbox = true
			} else {
				state.shopInfo.disableSandbox = false
			}
			if (info.hidePhone) {
				state.shopInfo.hidePhone = true
			} else {
				state.shopInfo.hidePhone = false
			}

			if (info.indexActivity) {
				state.shopInfo.indexActivity = info.indexActivity;
				state.shopInfo.isEnInvite = info.indexActivity.status == 0;
			} else {
				state.shopInfo.isEnInvite = false;
			}

			state.shopInfo.tools = info.functions || [];
			state.shopInfo.indexModals = info.indexModals ? info.indexModals : state.shopInfo.indexModals;
			state.shopInfo.userAgreeUrl = info.userAgreeUrl || ""
			state.shopInfo.privacyUrl = info.privacyUrl || ""
			state.shopInfo.projectId = info.projectId
			state.shopInfo.limitFollowDay = info.limitFollowDay
			state.shopInfo.panoramaUrl = info.panoramaUrl || state.shopInfo.panoramaUrl
			// state.shopInfo.panoramaUrl = 'http://192.168.212.138:8080/#/?pid=1000'
			state.shopInfo.news = info.news || state.shopInfo.news
			state.shopInfo.newsImagePath = info.newsImagePath || state.shopInfo.newsImagePath
			state.shopInfo.address = info.address || state.shopInfo.address
			state.shopInfo.name = info.name || state.shopInfo.name
			state.shopInfo.indexBigImage = info.indexBigImage || ''
			state.shopInfo.entranceImagePath = info.entranceImagePath || state.shopInfo.entranceImagePath
			state.shopInfo.trafficImagePath = info.trafficImagePath || state.shopInfo.trafficImagePath
			state.shopInfo.buildingImagePath = info.buildingImagePath || state.shopInfo.buildingImagePath
			state.shopInfo.contactImagePath = info.contactImagePath || state.shopInfo.contactImagePath
			state.shopInfo.unitTypeImagePath = info.unitTypeImagePath || state.shopInfo.unitTypeImagePath
			if (info.location.length > 0) {
				var m = info.location.split(",");
				state.shopInfo.location.latitude = m[1];
				state.shopInfo.location.longitude = m[0];
			}
			state.shopInfo.visitorNum = info.visitorNum || state.shopInfo.visitorNum
			state.shopInfo.layoutList = info.layout && info.layout.list || []
			state.shopInfo.authInfo = info.authInfo || []

			state.shopInfo.shareImage = info.shareImage || ''
			state.shopInfo.sandBoxImage = info.sandBoxImage || ''
			state.shopInfo.shareInfo = info.shareInfo || ''
			state.shopInfo.logo = info.logo || ''
			state.shopInfo.officalAccountUrl = info.officalAccountUrl
			if (info.projectId) {
				uni.setStorageSync('projectId', info.projectId)
			}

			if (info.authrizedOrder && info.authrizedOrder.length == 3) {
				state.shopInfo.authrizedOrder = info.authrizedOrder;
			}

			if (info.addCustomerManual) {
				state.shopInfo.addCustomerManual = info.addCustomerManual
			}

			if (info.wxappIndexWholeConfig) {
				state.shopInfo.wxappIndexWholeConfig.margin = info.wxappIndexWholeConfig.margin || state.shopInfo
					.wxappIndexWholeConfig.margin;
				state.shopInfo.wxappIndexWholeConfig.backgroundColor = info.wxappIndexWholeConfig.backgroundColor ||
					state.shopInfo.wxappIndexWholeConfig.backgroundColor;
				state.shopInfo.wxappIndexWholeConfig.vrTop = info.wxappIndexWholeConfig.vrTop || state.shopInfo
					.wxappIndexWholeConfig.vrTop;

				state.shopInfo.wxappIndexWholeConfig.pointerTop = info.wxappIndexWholeConfig.pointerTop || state
					.shopInfo.wxappIndexWholeConfig.pointerTop;
				state.shopInfo.wxappIndexWholeConfig.vrUrl = info.wxappIndexWholeConfig.vrUrl || state.shopInfo
					.wxappIndexWholeConfig.vrUrl;
				state.shopInfo.wxappIndexWholeConfig.pointerUrl = info.wxappIndexWholeConfig.pointerUrl || state
					.shopInfo.wxappIndexWholeConfig.pointerUrl;
				state.shopInfo.wxappIndexWholeConfig.moveUrl = info.wxappIndexWholeConfig.moveUrl || state.shopInfo
					.wxappIndexWholeConfig.moveUrl;
				state.shopInfo.wxappIndexWholeConfig.disableSandbox = info.wxappIndexWholeConfig.disableSandbox ||
					state.shopInfo.wxappIndexWholeConfig.disableSandbox;
			}
		},
		clearUserInfo(state) {
			state.hasLogin = false
			state.isAuthPhone = false
			state.isAuthUserInfo = false
			state.isExpires = false
			state.sellerObj.wechatCode = ""
			state.sellerObj.personSignature = ""
			state.sellerObj.name = ""
			state.sellerObj.nickname = ""
			state.sellerObj.avatar = "/static/img/user_img_ntx.png"
			state.sellerObj.phone = ""
			state.sellerObj.post = ""
			state.sellerObj.qrcodeImage = ""
			state.sellerObj.wechatQrcode = ""
			state.sellerObj.cardShareTitle = ""
			state.sellerObj.cardShareImage = ""
			state.sellerObj.officalAccountId = ""
			state.sellerObj.roleName = ""
		},
		setUserInfo(state, user) {		
			state.appAvatar = user.appAvatar||""
			state.appNickName = user.appNickName||""
			state.authTiktokInfo = user.dyAuth|false
			state.authTiktokPermission = user.mountPermission||false
			state.authTiktokPermissionValidStartTime=user.authTiktokPermissionValidStartTime
			state.authTiktokPermissionValidEndTime=user.authTiktokPermissionValidEndTime
			state.authTiktokAuthTime=user.authTime
			if (user.points && user.points > 0) {
				state.points = user.points
			} else {
				state.points = 0
			}

			if (user.appDisable) {
				state.isExpires = true
			} else {
				state.isExpires = false
			}

			if (user.isReferrer && user.isReferrer > 0) {
				state.isReferrer = true
			} else {
				state.isReferrer = false
			}

			if (user.channel && user.channel > 0) {
				state.isChannel = true
				state.isReferrer = false
			} else {
				state.isChannel = false
			}

			//==头像授权
			if ((user.avatar && user.avatar.length > 0) &&
				(user.nickname && user.nickname.length > 0)) {
				state.isAuthUserInfo = true
			} else {
				state.isAuthUserInfo = false
			}

			//==电话授权
			if (user.phone && user.phone.length > 0) {
				state.isAuthPhone = true
			} else {
				state.isAuthPhone = false
			}
			state.isSeller = user.isSeller

			if (state.isSeller > 0 && user.employInfo) {
				state.sellerObj.id = user.employInfo.id || '';
				state.sellerObj.uuid = user.id || '';
				state.sellerObj.avatar = user.avatar || state.sellerObj.avatar;
				state.sellerObj.qrcodeImage = user.qrcodeImage || state.sellerObj.qrcodeImage;
				state.sellerObj.wechatQrcode = user.employInfo.wechatQrcode || '';
				state.sellerObj.phone = user.phone || state.sellerObj.phone;
				state.sellerObj.post = user.employInfo.post || state.sellerObj.post;
				state.sellerObj.name = user.employInfo.name || state.sellerObj.name;
				state.sellerObj.nickname = user.nickname || state.sellerObj.nickname;
				state.sellerObj.wechatCode = user.wechatCode || state.sellerObj.wechatCode;
				state.sellerObj.personSignature = user.personSignature || state.sellerObj.personSignature;
				state.sellerObj.officalAccountId = user.mpOpenid || "";
				state.sellerObj.cardShareTitle = user.employInfo.shareInfo || '';
				state.sellerObj.cardShareImage = user.employInfo.shareImg || '';
				state.sellerObj.roleName = user.roleName || '';
			}

			state.buyerObj.id = user.id || '';
			state.buyerObj.uuid = user.id || '';
			state.buyerObj.avatar = user.avatar || state.buyerObj.avatar;
			state.buyerObj.phone = user.phone || state.buyerObj.phone;
			state.buyerObj.name = user.nickname || state.buyerObj.name;
			state.buyerObj.salesmanId = user.salesmanId || state.buyerObj.salesmanId
			state.buyerObj.channelId = user.channelId || state.buyerObj.channelId
			state.buyerObj.salesmanEmployId = user.salesmanEmployId || state.buyerObj.salesmanEmployId
			state.buyerObj.salesmanName = user.salesmanName || state.buyerObj.salesmanName
			state.buyerObj.officalAccountId = user.mpOpenid || "";

			state.openid = user.openid || "";
			uni.setStorageSync('openid', state.openid)
		},

		setLoginStatus(state, status) {
			state.hasLogin = status
		},

		clearOrigin(state) {
			state.originId = "";
			state.origin = "";
		},

		setOrigin(state, status) {
			state.originId = status.originId;
			state.origin = status.origin;
		},
		setLocation(state) {
			state.isAuthLocation = true;
		},
		setReferrer(state) {
			state.isReferrer = true
		},
		setExpires(state) {
			state.isExpires = state
		},
		//===积分
		setPoints(state, status) {
			state.points = status
		}

	},


	actions: {		
		loginWechat(context) {
			let that = this

			if (!uni.getStorageSync("projectId")) {
				uni.setStorageSync("projectId", "1000")
			}
			console.log("loginWechat:", "1")

			return new Promise(function(resolve, reject) {
				console.log("loginWechat:", "2")
				uni.showLoading({
					title: '正在加载...'
				});

				uni.login({
					provider: 'univerify',
					univerifyStyle: {
						fullScreen: true
					},
					success: response => {
						let openid = uni.getStorageSync("openid");
						console.log("loginWechat:", response)
						if (response.code) {
							// 发送 res.code 到后台换取 openId, sessionKey, unionId
							api.login({
								param: {
									code: response.code,
									appid: Config.appId,
									tenantCode: uni.getStorageSync("projectId"),
									logId: uni.getStorageSync("logId"),
									// openId: uni.getStorageSync("openid"),
									// projectId: uni.getStorageSync("projectId"),

									// originId: context.state.originId,
									// origin: context.state.origin,
								}
							}).then(res => {
								console.log("loginWechat:", res)
								if (res.success) {
									context.commit("clearOrigin")
									uni.setStorageSync('Authorization', res.data)

									api.getUserInfo().then(res => {
										if (res.success) {
											console.log(res)
											context.commit('setUserInfo', res
												.data)
											context.commit('setLoginStatus',
												true)

											api.getProjectInfo({
												param: {
													//===1 预览模式，  0 正常模式
													preview: uni
														.getStorageSync(
															"previewMode"
															)
												}
											}).then(res => {
												console.log(res)
												if (res.success) {
													context.commit(
														'setShopInfo',
														res.data)
													resolve()
												} else {
													resolve()
												}
											}).catch(res => {
												resolve()
											})

											uni.hideLoading();
											// resolve()
										} else {
											console.log(
												'loginWechat->getUserInfo接口失败:',
												res)
											uni.hideLoading();
											reject()
										}
									}).catch(err => {
										uni.hideLoading();
										reject()
									})

								} else {
									console.log('loginWechat->login接口失败:', err)
									uni.hideLoading();
									reject()
								}
							}).catch(() => {
								uni.hideLoading();
								console.log("url参数错误！！")
								reject()
							})

						} else {
							uni.hideLoading();
							reject()
							uni.showModal({
								title: '提示',
								content: '微信登录失败:' + response.errMsg,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}
					},
					fail:function(e) {
						console.log("loginWechat:", e)
						reject(1)
						uni.hideLoading();
					},
					complete: function() {
						// uni.hideLoading();
					}
				});

			});

		},


		phoneAuth(context, ev) {
			let that = this
			return new Promise(function(resolve, reject) {
				uni.showLoading({
					title: '正在授权...'
				});
				uni.login({
					success: response => {
						console.log("authPhone:", response, ev)
						if (response.code) {
							// 发送 res.code 到后台换取 openId, sessionKey, unionId
							api.authPhone({
								param: {
									appid: Config.appId,
									code: response.code,
									encryptedData: ev.encryptedData,
									iv: ev.iv,
								}
							}).then(res => {
								console.log("phoneAuth:", res)
								// context.commit('setPhoneAuth', true)
								api.getUserInfo().then(res => {
									if (res.success) {
										console.log(res)
										context.commit('setUserInfo', res.data)
										context.commit('setLoginStatus', true)
										resolve()
									} else {
										uni.showToast({
											icon: 'none',
											title: '登录失败，在我的页面里点击【退出小程序】',
											// duration:'2000'
										})
										reject()
									}
								}).catch(err => {
									console.log(err)
									reject()
								})
							}).catch(() => {
								console.log("url参数错误！！")
							})

						} else {
							reject()
							uni.showModal({
								title: '提示',
								content: '微信授权失败:' + response.errMsg,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						}
					},
					complete() {
						uni.hideLoading();
					}
				});
			});
		},

		interceptorLoginPhoneAuth(context, Obj) {
			if (context.state.hasLogin) {
				if (context.state.isAuthPhone) {
					Obj.success && typeof Obj.success == 'function' && Obj.success();
				} else {
					Obj.auth && typeof Obj.auth == 'function' && Obj.auth();
				}
			}
		},

		interceptorLoginInfoAuth(context, callback) {
			function authConduct() {
				if (context.state.isAuthUserInfo) {
					typeof callback == 'function' && callback();
				} else {
					if (uni.getUserProfile) {
						uni.getUserProfile({
							lang: 'zh_CN',
							desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
							success: (res) => {

								api.updateUserInfo({
									param: {
										nickname: res.userInfo.nickName || "",
										avatar: res.userInfo.avatarUrl || "",
										// province: res.userInfo.province || "",
										// city: res.userInfo.city || "",
										// country: res.userInfo.country || "",
										// gender: res.userInfo.gender.toString() || "",
									}
								}).then(res => {
									if (res.success) {
										api.getUserInfo().then(res => {
											if (res.success) {
												console.log(res)
												context.commit('setUserInfo', res.data)
												context.commit('setLoginStatus', true)
												typeof callback == 'function' &&
													callback();
											} else {
												uni.showToast({
													icon: 'none',
													title: '登录失败，在我的页面里点击【退出小程序】',
													// duration:'2000'
												})
											}
										}).catch(err => {

										})
									}
								})
							},
							fail: (res) => {
								console.log(res)
							}
						})
					} else {
						typeof callback == 'function' && callback();
					}

				}
			}

			if (context.state.hasLogin) {
				authConduct()
			} else {
				context.dispatch('loginWechat').then(() => {
					authConduct()
				})
			}
		},

	}
}
export default userModules